//
//  BasecampConduit.m
//  Task Views
//
//  Created by Chris Karr on 2/23/09.
//  Copyright 2009 Chris J. Karr. All rights reserved.
//

#import "BasecampConduit.h"


@implementation BasecampConduit

- (NSArray *) fetchTasks:(NSDictionary *) options
{
	NSBundle * bundle = [NSBundle mainBundle];
	
	NSString * script = [bundle pathForResource:@"conduit" ofType:@"rb" inDirectory:@"Conduits/basecamp_conduit"];
	
	NSPipe * stdoutPipe = [NSPipe pipe];
	NSFileHandle * out = [stdoutPipe fileHandleForReading];
	
	NSTask * task = [[NSTask alloc] init];
	[task setLaunchPath:@"/usr/bin/ruby"];
	[task setCurrentDirectoryPath:[script stringByDeletingLastPathComponent]];

	NSMutableArray * args = [NSMutableArray arrayWithObjects:@"-Ilib", script, [options valueForKey:@"site"], [options valueForKey:@"username"], 
							 [options valueForKey:@"password"], nil];
	
	if ([options valueForKey:@"milestones"] == nil || [[options valueForKey:@"milestones"] boolValue])
		[args addObject:@"yes"];
	else
		[args addObject:@"no"];

	if ([options valueForKey:@"todos"] == nil || [[options valueForKey:@"todos"] boolValue])
		[args addObject:@"yes"];
	else
		[args addObject:@"no"];
	
	[task setArguments:args];
	[task setStandardOutput:stdoutPipe];
	
	[task launch];

	NSMutableData * xmlIn = [NSMutableData data];
	
	while ([task isRunning])
	{
		NSData * data = nil;
		
		do
		{
			data = [out readDataOfLength:16384];
			
			[xmlIn appendData:data];
			
		}
		while ([data length] > 0);
	}

	[out closeFile];
	[task release];

	NSXMLDocument * xml = [[NSXMLDocument alloc] initWithData:xmlIn options:NSXMLDocumentTidyXML error:nil];

	NSXMLElement * lists = [xml rootElement];
	
	NSMutableArray * tasks = [NSMutableArray array];

	NSEnumerator * iter = [[lists elementsForName:@"list"] objectEnumerator];
	NSXMLElement * list = nil;
	while (list = [iter nextObject])
	{
		NSEnumerator * taskIter = [[list elementsForName:@"task"] objectEnumerator];
		NSXMLElement * task = nil;
		while (task = [taskIter nextObject])
		{
			NSMutableDictionary * taskDict = [NSMutableDictionary dictionary];
			[taskDict setValue:[[list attributeForName:@"name"] stringValue] forKey:@"Project"];
			[taskDict setValue:[[list attributeForName:@"name"] stringValue] forKey:@"List"];
			[taskDict setValue:[[lists attributeForName:@"name"] stringValue] forKey:@"source"];
			
			NSEnumerator * attIter = [[task attributes] objectEnumerator];
			NSXMLNode * attribute = nil;
			while (attribute = [attIter nextObject])
			{
				NSString * name = [[attribute name] stringByReplacingOccurrencesOfString:@"-" withString:@"_" 
																				 options:NSCaseInsensitiveSearch 
																				   range:NSMakeRange(0, [[attribute name] length])];
				
				[taskDict setValue:[attribute stringValue] forKey:[attribute name]];
				
				if ([name isEqual:@"content"])
					[taskDict setValue:[attribute stringValue] forKey:@"name"];
				else if ([name isEqual:@"title"])
					[taskDict setValue:[attribute stringValue] forKey:@"name"];
				else if ([name isEqual:@"created_on"])
				{
					NSDate * date = [NSDate dateWithNaturalLanguageString:[attribute stringValue]];
					[taskDict setValue:date forKey:@"created_on"];
				}
				else if ([name isEqual:@"deadline"])
				{
					NSDate * date = [NSDate dateWithNaturalLanguageString:[attribute stringValue]];
					[taskDict setValue:date forKey:@"deadline"];
				}
				else if ([name isEqual:@"completed_on"])
				{
					NSDate * date = [NSDate dateWithNaturalLanguageString:[attribute stringValue]];
					[taskDict setValue:date forKey:@"completed_on"];
				}
				else if ([name isEqual:@"position"])
				{
					NSScanner * scanner = [NSScanner scannerWithString:[attribute stringValue]];
					
					long long valueToGet;
					
					if ([scanner scanLongLong:&valueToGet] == YES) 
						[taskDict setValue:[NSNumber numberWithLongLong:valueToGet] forKey:@"position"];
				}
			}
			
			[tasks addObject:taskDict];
		}
	}
	
	[xml release];
	
	return tasks;
}

- (void) openExternalSite:(NSDictionary *) options
{
	NSURL * url = [NSURL URLWithString:[NSString stringWithFormat:@"https://%@/", [options valueForKey:@"site"], nil]];
	
	[[NSWorkspace sharedWorkspace] openURL:url];
}

@end
